package com.storage.system.service.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.storage.common.core.domain.AjaxResult;
import com.storage.common.core.domain.ServiceResponse;
import com.storage.common.core.page.TableDataInfo;
import com.storage.common.core.text.Convert;
import com.storage.common.enums.OwnerType;
import com.storage.common.enums.RoleType;
import com.storage.common.utils.DateUtils;
import com.storage.common.utils.GsonUtil;
import com.storage.system.domain.*;
import com.storage.system.mapper.StorageGoodsMapper;
import com.storage.system.mapper.StorageImageMapper;
import com.storage.system.mapper.StorageProductMapper;
import com.storage.system.mapper.StorageShopOrderMapper;
import com.storage.system.service.IStorageShopOrderService;
import com.storage.system.utils.GoodsConvertUtils;
import com.storage.system.vo.SellDetailInfo;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 店铺销售订单 服务层实现
 *
 * @author ruoyi
 * @date 2019-08-26
 */
@Service
public class StorageShopOrderServiceImpl implements IStorageShopOrderService {

    @Autowired
    private StorageShopOrderMapper storageShopOrderMapper;

    @Autowired
    private StorageProductMapper storageProductMapper;

    @Autowired
    private StorageGoodsMapper storageGoodsMapper;

    @Autowired
    private StorageImageMapper storageImageMapper;

    /**
     * 查询店铺销售订单信息
     *
     * @param id 店铺销售订单ID
     * @return 店铺销售订单信息
     */
    @Override
    public StorageShopOrder selectStorageShopOrderById(Long id) {
        return storageShopOrderMapper.selectStorageShopOrderById(id);
    }

    /**
     * 查询店铺销售订单列表
     *
     * @param storageShopOrder 店铺销售订单信息
     * @return 店铺销售订单集合
     */
    @Override
    public ServiceResponse<TableDataInfo> selectStorageShopOrderList(StorageUser currUser, StorageShopOrder storageShopOrder, Integer pageNum, Integer pageSize) {
        Long operationUserId = RoleType.getOperationUserId(currUser.getRole(), currUser.getId(), currUser.getShopId());
        storageShopOrder.setCreateUserId(operationUserId);

        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }

        Integer start = (pageNum - 1) * pageSize;
        // 查询查询分页数据
        List<StorageShopOrder> orders = storageShopOrderMapper.queryPageList(storageShopOrder, start, pageSize);
        // 查询 totalCount
        Long totalCount = storageShopOrderMapper.queryPageCount(storageShopOrder);
        if (orders == null) {
            return null;
        }

        TableDataInfo pageList = new TableDataInfo(orders, totalCount, pageNum, pageSize);
        return new ServiceResponse<>(true, pageList, null);
    }

    /**
     * 新增店铺销售订单
     *
     * @param storageShopOrder 店铺销售订单信息
     * @return 结果
     */
    @Override
    public int insertStorageShopOrder(StorageShopOrder storageShopOrder) {
        return storageShopOrderMapper.insertStorageShopOrder(storageShopOrder);
    }

    /**
     * 修改店铺销售订单
     *
     * @param storageShopOrder 店铺销售订单信息
     * @return 结果
     */
    @Override
    public AjaxResult updateStorageShopOrder(StorageUser currUser, StorageShopOrder storageShopOrder) {
        if (storageShopOrder.getId() != null) {
            storageShopOrderMapper.updateStorageShopOrder(storageShopOrder);
        } else {
            // 生成订单编号
            storageShopOrder.setOrderCode(getOrderCode());
            storageShopOrderMapper.insertStorageShopOrder(storageShopOrder);
            // 相应的库存数量减少
            reduceShopStock(currUser, storageShopOrder);

        }
        return AjaxResult.success();
    }

    /**
     * 临时销售减去店铺库存
     *
     * @param currUser
     * @param storageShopOrder
     * @return
     */
    private ServiceResponse<Boolean> reduceShopStock(StorageUser currUser, StorageShopOrder storageShopOrder) {
        Gson gson = GsonUtil.getGson();
        List<StorageProduct> storageProducts = gson.fromJson(storageShopOrder.getGoodsContent(), new TypeToken<List<StorageProduct>>() {}.getType());
        for (StorageProduct product : storageProducts) {
            // 查询出库存商品减去
            StorageProduct sourceProduct = storageProductMapper.selectStorageProductById(product.getId());
            // 更新实时库存
            sourceProduct.setRealTimeGoodsNum(sourceProduct.getRealTimeGoodsNum() - product.getRealTimeGoodsNum());
            storageProductMapper.updateStorageProduct(sourceProduct);

            List<StorageGoods> orderGoods = product.getGoods();
            if (orderGoods == null) {
                continue;
            }
            for (StorageGoods goods : orderGoods) {
                // 查询出库存单品减去
                StorageGoods sourceGoods = storageGoodsMapper.selectStorageGoodsById(goods.getId());
                // 更新单品库存
                sourceGoods.setStockNum(sourceGoods.getStockNum() - goods.getStockNum());
                storageGoodsMapper.updateStorageGoods(sourceGoods);

                GoodsConvertUtils.checkWarning(sourceGoods, sourceProduct);
            }

        }
        return new ServiceResponse<>(true, null, null);
    }

    /**
     * 产生订单编号
     * @return
     */
    private String getOrderCode() {
        String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String rannum = RandomStringUtils.randomNumeric(4);
        return date + rannum;
    }

    /**
     * 删除店铺销售订单对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteStorageShopOrderByIds(String ids) {
        return storageShopOrderMapper.deleteStorageShopOrderByIds(Convert.toStrArray(ids));
    }

    /**
     * 查询店铺 商品销售数据列表
     */
    @Override
    public ServiceResponse<TableDataInfo> getShopSellDetail(StorageUser storageUser, StorageShopOrder shopOrder, Date startTime, Date endTime, Integer pageNum, Integer pageSize) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }

        // 查询出所有订单
        StorageShopOrder orderCondition = new StorageShopOrder();
        orderCondition.setShopId(shopOrder.getShopId());
        orderCondition.setStartTime(startTime);
        orderCondition.setEndTime(endTime);
        List<StorageShopOrder> orders = storageShopOrderMapper.selectStorageShopOrderList(orderCondition);
        if (orders == null || orders.size() == 0) {
            List<StorageProduct> pagingList = new ArrayList<>();
            TableDataInfo pageList = new TableDataInfo(pagingList, 0L, pageNum, pageSize);
            return new ServiceResponse<>(true, pageList, null);
        }

        // 查询指定店铺有的商品列表
        StorageProduct condition = new StorageProduct();
        condition.setOwnerType(OwnerType.SHOP.getValue());
        condition.setCreateUserId(shopOrder.getShopId());
        List<StorageProduct> products = storageProductMapper.selectStorageProductList(condition);
        Gson gson = GsonUtil.getGson();

        // 统计货号以及对应货号销售数量
        Map<String, LongSummaryStatistics> map = orders.stream().map(order -> {
            List<StorageProduct> storageProducts = gson.fromJson(order.getGoodsContent(), new TypeToken<List<StorageProduct>>() {}.getType());
            return storageProducts;
        }).flatMap(item -> item.stream()).collect(Collectors.groupingBy(StorageProduct::getProductSpuCode, Collectors.summarizingLong(StorageProduct::getRealTimeGoodsNum)));

        // 和当前已有库存商品做匹配
        List<StorageProduct> results = products.stream().map(item -> {
            if (map.containsKey(item.getProductSpuCode())) {
                item.setSellCount(map.get(item.getProductSpuCode()).getSum());
            } else {
                item.setSellCount(0L);
            }
            return item;
        }).sorted(Comparator.comparing(StorageProduct::getSellCount).reversed()).collect(Collectors.toList());

        // 计算分页
        int fromIdx = (pageNum - 1) * pageSize;
        int toIdx = pageNum * pageSize > results.size() ? results.size() : pageNum * pageSize;
        List<StorageProduct> pagingList = results.subList(fromIdx, toIdx).stream().map(item -> {
            // 查询对应产品的图片集合
            StorageImage imageCondition = new StorageImage();
            imageCondition.setLinkProductId(item.getId());
            List<StorageImage> images = storageImageMapper.selectStorageImageList(imageCondition);
            item.setImages(images);
            return item;
        }).collect(Collectors.toList());
        TableDataInfo pageList = new TableDataInfo(pagingList, new Long(results.size()), pageNum, pageSize);
        return new ServiceResponse<>(true, pageList, null);
    }


    @Override
    public ServiceResponse<List<SellDetailInfo>> queryShopHomePageData(StorageUser storageUser, StorageShopOrder order) {
        List<StorageShopOrder> results = storageShopOrderMapper.selectStorageShopOrderList(order);
        List<SellDetailInfo> sellDetailInfos = results.stream()
                .collect(Collectors.groupingBy(shopOrder -> DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, shopOrder.getCreateTime())))
                .entrySet().stream().map(e -> {
                    List<StorageShopOrder> tempOrders = e.getValue();
                    BigDecimal totalMoney = new BigDecimal(0);
                    for (StorageShopOrder tempOrder : tempOrders) {
                        totalMoney = totalMoney.add(tempOrder.getOrderTotalPrice());
                    }
                    return new SellDetailInfo(DateUtils.dateTime(DateUtils.YYYY_MM_DD, e.getKey()), tempOrders.size(), totalMoney, tempOrders);
                }).collect(Collectors.toList());

        return new ServiceResponse<>(true, sellDetailInfos, null);
    }
}
